//
//  AKToolKit.m
//  AKPZ
//
//  Created by Lexi on 16-3-14.
//  Copyright (c) 2016年 aikangpeizhen. All rights reserved.
//

#import "AKToolKit.h"
#import <CommonCrypto/CommonDigest.h>

@implementation AKToolKit

+ (void)showErrorMessage:(NSError *)error {
    NSInteger errorCode = error.code;
    if (errorCode == -999);//不做任何操作, -999表示用户取消了请求
    else if (errorCode == -1001)[AKUIToolKit alertMessage:NETWORK_TIMEOUT_MESSAGE];  //超时
    else if (errorCode == -1004)[AKUIToolKit alertMessage:NETWORK_LOSS_CONNECTION]; //未连接到服务器
    else if (errorCode == -1009)[AKUIToolKit alertMessage:NETWORK_NO_NET_MESSAGE];  //无网络
    else if (errorCode == NET_CODE_USER_IS_EXISTED)[AKUIToolKit alertMessage:@"用户已存在"];
    else if (errorCode == NET_CODE_USER_IS_NOT_EXISTED)[AKUIToolKit alertMessage:@"用户名或密码错误"];
    else if (errorCode == NET_CODE_PHONE_IS_NOT_EXISTED)[AKUIToolKit alertMessage:@"手机号不存在"];
    else if (errorCode == NET_CODE_AUTHCODE_INVALID)[AKUIToolKit alertMessage:@"验证码错误"];
    else if (errorCode == NET_CODE_USER_ADD_FAIL)[AKUIToolKit alertMessage:@"添加用户失败, 请联系管理员"];
    else if (errorCode == NET_CODE_USER_DELETE_FAIL)[AKUIToolKit alertMessage:@"删除用户失败, 请联系管理员"];
    else if (errorCode == NET_CODE_USER_UPDATE_FAIL)[AKUIToolKit alertMessage:@"修改用户失败, 请联系管理员"];
    else if (errorCode == NET_CODE_USER_QUERY_FAIL)[AKUIToolKit alertMessage:@"查询用户失败, 请联系管理员"];
    else if (errorCode == NET_CODE_PWD_INCORRECT)[AKUIToolKit alertMessage:@"原密码错误"];
    else if (errorCode == NET_CODE_DEVICE_IS_EXISTED)[AKUIToolKit alertMessage:@"设备已存在"];
    else if (errorCode == NET_CODE_DEVICE_IS_NOT_EXISTED)[AKUIToolKit alertMessage:@"设备不存在"];
    else if (errorCode == NET_CODE_DEVICE_ACTIVE_FAIL)[AKUIToolKit alertMessage:@"激活设备失败, 请联系管理员"];
    else if (errorCode == NET_CODE_DEVICE_UPDATE_FAIL)[AKUIToolKit alertMessage:@"修改设备失败, 请联系管理员"];
    else if (errorCode == NET_CODE_DEVICE_QUERY_FAIL)[AKUIToolKit alertMessage:@"查询设备失败, 请联系管理员"];
    else if (errorCode == NET_CODE_DEVICE_CANT_ACTIVED)[AKUIToolKit alertMessage:@"开通设备失败, 设备已存在且未解绑"];
    else if (errorCode == NET_CODE_SITE_IS_NOT_EXISTED)[AKUIToolKit alertMessage:@"商家门户不存在"];
    else if (errorCode == NET_CODE_FILE_PATH_INVALID)[AKUIToolKit alertMessage:@"文件路径错误, 请联系管理员"];
    else if (errorCode == NET_CODE_AUTHCODE_SEND_ERROR)[AKUIToolKit alertMessage:@"发送验证码失败, 请联系管理员"];
    else if (errorCode == NET_CODE_BILL_IS_NOT_EXISTED)[AKUIToolKit alertMessage:@"账单不存在"];
    else if (errorCode == NET_CODE_BILL_QUERY_FAIL)[AKUIToolKit alertMessage:@"账单查询失败, 请联系管理员"];
    else if (errorCode == NET_CODE_BILL_QUERY_PAY_FAIL)[AKUIToolKit alertMessage:@"支付查询失败, 请联系管理员"];
    else if (errorCode == NET_CODE_BUSINESS_IS_NOT_EXISTED)[AKUIToolKit alertMessage:@"业务不存在"];
    else if (errorCode == NET_CODE_BALANCE_NOT_ENOUGH)[AKUIToolKit alertMessage:@"余额不足"];
    else if (errorCode == NET_CODE_PAY_FAIL)[AKUIToolKit alertMessage:@"支付失败"];
    else if (errorCode == NET_CODE_BUSINESS_QUERY_FAIL)[AKUIToolKit alertMessage:@"查询业务失败, 请联系管理员"];
    else if (errorCode == NET_CODE_RECHARGE_FAIL)[AKUIToolKit alertMessage:@"充值失败"];
    else if (errorCode == NET_CODE_TEMPLATE_QUERY_FAIL)[AKUIToolKit alertMessage:@"模板查询失败, 请联系管理员"];
    else if (errorCode == NET_CODE_MERCHANT_IS_NOT_EXISTED)[AKUIToolKit alertMessage:@"门户不存在"];
    else if (errorCode == NET_CODE_TEMPLATE_IS_NOT_EXISTED)[AKUIToolKit alertMessage:@"模板不存在"];
    else if (errorCode == NET_CODE_TEMPLATE_SET_FAIL)[AKUIToolKit alertMessage:@"设置模板错误, 请联系管理员"];
    else if (errorCode == NET_CODE_PIC_MISSING)[AKUIToolKit alertMessage:@"图片不存在"];
    else if (errorCode == NET_CODE_ADV_IS_NOT_EXISTED)[AKUIToolKit alertMessage:@"广告不存在"];
    else if (errorCode == NET_CODE_URL_NOT_FOUND)[AKUIToolKit alertMessage:@"找不到站点URL"];
    else if (errorCode == NET_CODE_PIC_NOT_FOUND)[AKUIToolKit alertMessage:@"找不到对应的图片地址"];
    else if (errorCode == NET_CODE_TOKEN_EXPIRED) {
        [AKUIToolKit alertMessage:@"用户信息过期, 请重新登录"];
        [[AKClient sharedInstance] handleLogoutDone];
    }
    else [AKUIToolKit alertMessage:NETWORK_ERROR_MESSAGE];
}

#pragma mark - 工具

+ (BOOL)objectIsNull:(NSObject *)obj {
    if (obj != [NSNull null] && obj != nil) {
        return NO;
    } else {
        return YES;
    }
}

+ (BOOL)objectIsBlank:(NSObject *)obj {
    if (obj != [NSNull null] && obj != nil && ![obj isKindOfClass:[NSString class]] && ![(NSString *)obj isEqualToString:@""]) {
        return YES;
    } else {
        return NO;
    }
}

+ (BOOL)stringIsEmpty:(NSString *)aString shouldCleanWhiteSpace:(BOOL)cleanWhileSpace {
    if ((NSNull *) aString == [NSNull null]) {
        return YES;
    }
    if (aString == nil) {
        return YES;
    }
    else if ([aString length] == 0) {
        return YES;
    }
    if (cleanWhileSpace) {
        aString = [aString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([aString length] == 0) {
            return YES;
        }
    }
    return NO;
}

+ (NSString *)createUuidString {
    NSString *uuid = nil;
    if (IOS6) {
        uuid = [[NSUUID UUID] UUIDString];
    } else {
        CFUUIDRef UUID = CFUUIDCreate(NULL);
        uuid = CFBridgingRelease(CFUUIDCreateString(NULL, UUID));
        CFRelease(UUID);
    }
    return uuid;
}

+ (void)postNotify:(NSString*)type object:(id)obj {
    NSNotification *notification = [NSNotification notificationWithName:type object:obj];
    [[NSNotificationCenter defaultCenter] performSelectorOnMainThread: @selector(postNotification:) withObject:notification waitUntilDone:NO];
}

+ (NSString *)md5HexDigest:(NSString *)data {
    const char *cStr = [data UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (unsigned int)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+ (NSString *)replacePhoneCharacters:(NSString *)originalString {
    if (originalString.length >= 3) {
        NSString *_86String = [originalString substringWithRange:NSMakeRange(0, 3)];
        if ([_86String isEqualToString:@"+86"]) {   //去除+86
            originalString = [originalString stringByReplacingOccurrencesOfString:_86String withString:@""];
        }
    }
    
    NSRange range = [originalString rangeOfString:@"("];
    if (range.location != NSNotFound) {
        originalString = [originalString stringByReplacingCharactersInRange:range withString:@""];
    }
    range = [originalString rangeOfString:@")"];
    if (range.location != NSNotFound) {
        originalString = [originalString stringByReplacingCharactersInRange:range withString:@""];
    }
    
    range = [originalString rangeOfString:@"+"];
    if (range.location != NSNotFound) {
        originalString = [originalString stringByReplacingCharactersInRange:range withString:@""];
    }
    
    range = [originalString rangeOfString:@"."];
    while (range.location != NSNotFound) {
        originalString = [originalString stringByReplacingCharactersInRange:range withString:@""];
        range = [originalString rangeOfString:@" "];
    }
    
    originalString = [originalString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //空白和换行
    originalString = [originalString stringByReplacingOccurrencesOfString:@" " withString:@""]; //空格
    originalString = [originalString stringByReplacingOccurrencesOfString:@"-" withString:@""]; //-
    
    NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString:@"01234567890"] invertedSet];   //数字
    originalString = [originalString stringByTrimmingCharactersInSet:set];
    
    set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\""];   //特殊字符
    originalString = [originalString stringByTrimmingCharactersInSet:set];
    
    return originalString;
}

+ (UIColor *)colorWithHexString:(NSString *)stringToConvert {
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    if ([cString length] < 6) {
        return [UIColor whiteColor];
    }
    if ([cString hasPrefix:@"#"]) {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6) {
        return [UIColor whiteColor];
    }
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return RGBColor(r, g, b);
}

+ (NSString *)getFilePath:(NSString *)fileName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *onlinePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    return onlinePath;
}

+ (BOOL)createFile:(NSString *)fileName {
    DLog(@"create file:%@", fileName);
    NSString *online = [AKToolKit getFilePath:fileName];
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:online]) {
        return true;
    }
    NSError *error = nil;
    [manager createFileAtPath:online contents:nil attributes:nil];
    if (error) {
        DLog(@"create file :%@ failed, the error is:%@", fileName, error);
        return false;
    }
    return true;
}

#pragma mark - 图片处理

+ (NSString*)saveImage:(UIImage *)image toDocumentWithName:(NSString *)imageName fileType:(NSInteger)fileType {
    //    NSData *imageData = UIImageJPEGRepresentation(image, 1.f);
    //    switch (fileType) {
    //        case 0: {
    //            image = [XZCommonUtil resizeImage:image resizeSize:CGSizeMake(256.f, 256.f)];
    //            break;
    //        }
    //        case 1: {   //个人头像
    //            image = [XZCommonUtil resizeImage:image resizeSize:CGSizeMake(48.f, 48.f)];
    //            break;
    //        }
    //        case 2: {
    //            break;
    //        }
    //        case 3: {
    //            break;
    //        }
    //        case 4: {
    //            break;
    //        }
    //        case 5: {
    //            break;
    //        }
    //        case 6: {
    //            break;
    //        }
    //        case 7: {   //设形象
    //            image = [XZCommonUtil resizeImage:image resizeSize:CGSizeMake(64.f, 64.f)];
    //            break;
    //        }
    //        case 8: {
    //            break;
    //        }
    //        case 9: {
    //            break;
    //        }
    //        case 99: {
    //            break;
    //        }
    //        default:
    //            break;
    //    }
    image = [AKToolKit saveBitImage:image];
    NSData *imageData = UIImageJPEGRepresentation(image, 1.f);
    //    DLog(@"image data length:%ld", imageData.length);
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString* fullPathToFile = [DocumentsPath stringByAppendingPathComponent:imageName];
    [imageData writeToFile:fullPathToFile atomically:NO];
    return fullPathToFile;
}

+ (UIImage*)saveBitImage:(UIImage*)Image {
    NSData* dataImage = UIImageJPEGRepresentation(Image,1.0);
    NSUInteger sizeOrigin = [dataImage length];
    DLog(@"压缩前 :%f KB", (double)sizeOrigin / 1024);
    NSUInteger sizesizeOriginKB = sizeOrigin / 1024;
    float a = 250;
    float b = (float)sizesizeOriginKB;
    //    if (sizesizeOriginKB > 500)
    //    {
    //        a = 250;
    //    }
    //    else if(sizesizeOriginKB > 300)
    //    {
    //        a = 150;
    //    }
    //    else if(sizesizeOriginKB > 200)
    //    {
    //        a = 120;
    //    }
    //    else if(sizesizeOriginKB > 100)
    //    {
    //        a = 60;
    //    }
    
    float q = sqrt(a/b);
    // 图片大于500k要先进行压缩
    if (sizesizeOriginKB > 500)
    {
        DLog(@"q:%f",q);
        CGSize sizeImage = [Image size];
        CGFloat iwidthSmall = sizeImage.width * q;
        CGFloat iheightSmall = sizeImage.height * q;
        CGSize itemSizeSmall = CGSizeMake(iwidthSmall, iheightSmall);
        UIGraphicsBeginImageContext(itemSizeSmall);
        
        CGRect imageRectSmall = CGRectMake(0.0f, 0.0f, itemSizeSmall.width+2, itemSizeSmall.height+2);  //长和宽都增加2个像素，防止有些图片绘制旁边出现白线
        [Image drawInRect:imageRectSmall];
        
        UIImage *SmallImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        NSData *dataImageSend = UIImageJPEGRepresentation(SmallImage,0.85);
        
        dataImage = dataImageSend;
    }
    
    DLog(@"压缩后 :%f KB", (float)[dataImage length]/1024);
    return [UIImage imageWithData:dataImage];
}

//从document读取图片
+ (UIImage *)getImageFromDocumentWithName:(NSString *)imageName {
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *imagePath = [DocumentsPath stringByAppendingPathComponent:imageName];
    return [[UIImage alloc] initWithContentsOfFile:imagePath];
}

//删除documents中的指定图片
+ (void)deleteImageFromDocumentsWithName:(NSString *)imageName {
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *imagePath = [DocumentsPath stringByAppendingPathComponent:imageName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:imagePath error:nil];
}

//压缩图片
+ (UIImage *)scaleImage:(UIImage*)image toSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage *)compressedImage:(UIImage*)image toSize:(CGSize)newSize {
    CGSize imageSize = image.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    if (width <= newSize.width && height <= newSize.height) {
        return image;
    }
    
    if (width == 0 || height == 0) {
        return image;
    }
    
    UIImage *newImage = nil;
    CGFloat widthFactor = MAX_IMAGEPIX / width;
    CGFloat heightFactor = MAX_IMAGEPIX / height;
    CGFloat scaleFactor = 0.0;
    
    if (widthFactor > heightFactor)
        scaleFactor = heightFactor; // scale to fit height
    else
        scaleFactor = widthFactor; // scale to fit width
    
    CGFloat scaledWidth  = width * scaleFactor;
    CGFloat scaledHeight = height * scaleFactor;
    CGSize targetSize = CGSizeMake(scaledWidth, scaledHeight);
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [image drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIImage *rimage = [UIImage imageWithData:[self compressedData:newImage]];
    
    UIGraphicsEndImageContext();
    
    return rimage;
    
}

+ (NSData *)compressedData:(CGFloat)compressionQuality withImage:(UIImage*)image {
    assert(compressionQuality <= 1.0 && compressionQuality >= 0);
    return UIImageJPEGRepresentation(image, compressionQuality);
}

+ (CGFloat)compressionQuality:(UIImage*)image{
    NSData *data = UIImageJPEGRepresentation(image, 1.0);
    NSUInteger dataLength = [data length];
    if(dataLength > MAX_IMAGEDATA_LEN) {
        return 1.0 - MAX_IMAGEDATA_LEN / dataLength;
    } else {
        return 1.0;
    }
}

+ (NSData *)compressedData:(UIImage*)image {
    return [self compressedData:0.5 withImage:image];
}

+ (UIImage *)image:(UIImage *)image rotation:(UIImageOrientation)orientation {
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    
    switch (orientation) {
        case UIImageOrientationLeft:
            rotate = M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = 0;
            translateY = -rect.size.width;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationRight:
            rotate = 3 * M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = -rect.size.height;
            translateY = 0;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationDown:
            rotate = M_PI;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = -rect.size.width;
            translateY = -rect.size.height;
            break;
        default:
            rotate = 0.0;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = 0;
            translateY = 0;
            break;
    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    return newPic;
}

+ (UIImage *)resizeImage:(UIImage *)orginalImage resizeSize:(CGSize)size {
    CGFloat actualHeight = orginalImage.size.height;
    CGFloat actualWidth = orginalImage.size.width;
    float oldRatio = actualWidth/actualHeight;
    float newRatio = size.width/size.height;
    if (oldRatio < newRatio) {
        oldRatio = size.height/actualHeight;
        actualWidth = oldRatio * actualWidth;
        actualHeight = size.height;
    }
    else {
        oldRatio = size.width/actualWidth;
        actualHeight = oldRatio * actualHeight;
        actualWidth = size.width;
    }
    
    CGRect rect = CGRectMake(0.0,0.0,actualWidth,actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    [orginalImage drawInRect:rect];
    orginalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return orginalImage;
}

+ (UIImage *)circleImage:(UIImage*)image withParam:(CGFloat)inset {
    UIGraphicsBeginImageContext(image.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor clearColor].CGColor);
    CGRect rect = CGRectMake(inset, inset, image.size.width-inset, image.size.height-inset);
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);
    
    [image drawInRect:rect];
    CGContextAddEllipseInRect(context, rect);
    CGContextStrokePath(context);
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}

+ (UIImage *)circleImage:(UIImage*)image {
    UIGraphicsBeginImageContext(image.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor clearColor].CGColor);
    
    CGFloat width = MIN(image.size.width, image.size.height);
    CGRect rect = CGRectMake(floorf(image.size.width-width)/2,
                             floorf((image.size.height-width)/2),
                             width, width);
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);
    
    [image drawInRect:rect];
    CGContextAddEllipseInRect(context, rect);
    CGContextStrokePath(context);
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}

#pragma mark - 接口

+ (NSString *)createUrl:(NSString *)url {
    if ([[AKUserDefaults sharedInstance] dc]) {
        return [NSString stringWithFormat:@"%@?token=%@&dc=%@", url, [[AKUserDefaults sharedInstance] token], [[AKUserDefaults sharedInstance] dc]];
    } else {
        return [NSString stringWithFormat:@"%@?token=%@", url, [[AKUserDefaults sharedInstance] token]];
    }
}

#pragma mark - 验证

+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188  add 183,
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1([0-9][0-9]|5[0-35-9]|8[0-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188  add 183,
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[23478])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES)) {
        return YES;
    } else {
        return NO;
    }
}

+ (BOOL)isPhoneNumber:(NSString *)phoneNum {
    NSString *reg1 = @"^0\\d{2,3}-?\\d{7,8}$";
    NSString *reg2 = @"^(1[0-9])\\d{9}$";
    NSString *reg3 = @"(^(0\\d{2,3})(([-]|[ ])|)(\\d{7,8})$)|(^(0\\d{3})-(\\d{7})$)|(^(0\\d{2})-(\\d{8})-(\\d+)$)|(^(0\\d{3})-(\\d{7})-(\\d+)$)";
    NSPredicate *regextestReg1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg1];
    NSPredicate *regextestReg2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg2];
    NSPredicate *regextestReg3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg3];
    if ([regextestReg1 evaluateWithObject:phoneNum] == YES
        || [regextestReg2 evaluateWithObject:phoneNum] == YES
        || [regextestReg3 evaluateWithObject:phoneNum] == YES
        )
    {
        return YES;
    }
    return NO;
}

+ (BOOL)isCorrectPwd:(NSString *)pwd {
    NSString *reg = @"^([a-zA-Z0-9~!@#$%^&*]){4,16}$";
    NSPredicate *regextestReg = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
    return [regextestReg evaluateWithObject:pwd];
}

#pragma mark - 字

+ (int)wordCount:(NSString *)s {
    NSUInteger n = [s length];
    int i, l = 0, a = 0, b = 0;
    unichar c;
    for (i = 0; i < n; i++) {
        c = [s characterAtIndex:i];
        if (isblank(c)) {
            b ++;
        }
        else if (isascii(c)) {
            a ++;
        }
        else {
            l ++;
        }
    }
    if (a == 0 && l == 0) {
        return 0;
    } else {
        return l + (int)ceilf((float)(a + b)/2.0);
    }
}


@end
